package com.ioudi.digu.ds;

import com.ioudi.digu.dao.UserDAO;
import com.ioudi.digu.dsdistribute.AbstractDatasourceDistribute;
import com.ioudi.digu.dsdistribute.method.MethodInfo;
import com.ioudi.digu.memcached.MemcachedClient;

public class DatasourceDistribute extends AbstractDatasourceDistribute
{
	private UserDAO userDAO;
	
	private MemcachedClient memcachedClient;
	
	protected String preLookupDatasource(Object value)
	{
		String user = null;
		if(value instanceof  String)
		{
			user = (String)value;
		}
		if(user != null && memcachedClient != null)
		{
			Object cached = memcachedClient.get(MemcachedClient.ID_USER_DB + user);
			if(cached != null)
			{
				return (String)cached;
			}
		}
		return null;
	}
   	
	protected MethodInfo getLookupMethodInfo(Object value)
    {
    	MethodInfo info = null;
    	if(value instanceof  String)
    	{
    		info = new MethodInfo();
    		try
    		{
    			info.setMethod(userDAO.getClass().getMethod("getObject", String.class));
        		info.setTarget(userDAO);
        		info.setParams(new String[]{(String)value});	
    		}
    		catch(Exception e)
    		{
    			info = null;
    		}
    	}
    	return info;
    }
	
	protected void postLookupDatasource(Object value, String datasource)
	{
		String user = null;
		if(value instanceof  String)
		{
			user = (String)value;
		}
		if(datasource != null && user != null && memcachedClient != null)
		{
			memcachedClient.set(MemcachedClient.ID_USER_DB + user, datasource);
		}
	}
	
	public MemcachedClient getMemcachedClient()
	{
		return memcachedClient;
	}

	public void setMemcachedClient(MemcachedClient memcachedClient)
	{
		this.memcachedClient = memcachedClient;
	}

	
	public UserDAO getUserDAO()
	{
		return userDAO;
	}
	public void setUserDAO(UserDAO userDAO)
	{
		this.userDAO = userDAO;
	}
}
